import 'dart:ui';

import 'package:flutter/gestures.dart';

final GestureBinding? _gestureBinding = GestureBinding.instance;
final double _devicePixelRatio = window.devicePixelRatio;

final List<PointerEvent?> _queueEvents = List.filled(1024, null);

int _queueIndex = 0;
Type? _runtimeType;

void initEvent() {
  window.onPointerDataPacket = _handlePointerDataPacket;
}

void _handlePointerDataPacket(PointerDataPacket packet) {
  Iterable<PointerEvent> events =
      PointerEventConverter.expand(packet.data, _devicePixelRatio);

  for (var event in events) {
    if (event.runtimeType != _runtimeType) {
      _runtimeType = event.runtimeType;
      _queueEvents[_queueIndex++] = event;
    }
  }

  // 发送至webview的事件已经返回则处理队列
  _handleQueueEvents();
}

void _handleQueueEvents() {
  for (var i = 0; i < _queueIndex; i++) {
    PointerEvent? event = _queueEvents[i];

    if (event != null) {
      _handleEvent(event);
    }
  }

  _queueIndex = 0;
  _runtimeType = null;
}

void _handleEvent(PointerEvent event) {
  switch (event.kind) {
    case PointerDeviceKind.mouse:
      HitTestResult result = HitTestResult();
      _gestureBinding?.hitTest(result, event.position);
      print(result);
      break;

    case PointerDeviceKind.invertedStylus:
      break;

    case PointerDeviceKind.stylus:
      break;

    case PointerDeviceKind.touch:
      HitTestResult result = HitTestResult();
      _gestureBinding?.hitTest(result, event.position);
      break;

    case PointerDeviceKind.unknown:
      break;
  }
}
